package cn.accjiyun.controller.production;

import cn.accjiyun.common.controller.BaseController;
import cn.accjiyun.common.entity.PageModel;
import cn.accjiyun.common.entity.QueryEntity;
import cn.accjiyun.common.utils.WebUtils;
import cn.accjiyun.entity.production.CropCare;
import cn.accjiyun.entity.production.Land;
import cn.accjiyun.entity.society.SocietyUser;
import cn.accjiyun.service.production.CropCareService;
import cn.accjiyun.service.production.LandService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiyun on 2017/5/3.
 */
@Controller
@RequestMapping("/admin/production")
public class AdminCropCareController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AdminCropCareController.class);
    private static String addCropCarePage = getViewPath("/admin/production/cropCare-add");
    private static String cropCareListPage = getViewPath("/admin/production/cropCare-list");

    @Autowired
    private CropCareService cropCareService;
    @Autowired
    private LandService landService;

    @InitBinder({"cropCare"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("cropCare.");
    }

    /**
     * 创建作物护理
     *
     * @return Map<String,Object>
     */
    @RequestMapping("/createCropCare")
    @ResponseBody
    public String createCropCare(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            int landId = Integer.valueOf(request.getParameter("landId"));
            Land land = landService.queryLandById(landId);
            Integer batch = Integer.valueOf(request.getParameter("batch"));
            String principalName = request.getParameter("principalName");
            String germchit = request.getParameter("germchit");
            Integer count = Integer.valueOf(request.getParameter("count"));
            String fertilizer = request.getParameter("fertilizer");
            String drug = request.getParameter("drug");
            Timestamp cropTime = WebUtils.stringToTimestamp(request.getParameter("cropTime"));

            CropCare cropCare = new CropCare();
            cropCare.setLandByLandId(land);
            cropCare.setBatch(batch);
            cropCare.setPrincipalName(principalName);
            cropCare.setGermchit(germchit);
            cropCare.setCount(count);
            cropCare.setFertilizer(fertilizer);
            cropCare.setDrug(drug);
            cropCare.setCropTime(cropTime);

            cropCareService.createCropCare(cropCare);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/production/cropCareList");
        } catch (Exception e) {
            logger.error("AdminCropCare.createCropCare()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/deleteCropCare")
    @ResponseBody
    public String deleteCropCare(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] cropCareIdsString = request.getParameter("cropCareId").split(",");
            int[] cropCareIds = new int[cropCareIdsString.length];
            for (int i = 0; i < cropCareIdsString.length; i++) {
                cropCareIds[i] = Integer.valueOf(cropCareIdsString[i]);
            }
            if (cropCareIdsString != null && cropCareIdsString.length > 0) {
                cropCareService.deleteCropCare(cropCareIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminCropCareController.deleteCropCare()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/getCropCareList")
    @ResponseBody
    public String getCropCareList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryEntity queryEntity = new QueryEntity();
            Map likeStrings = new HashMap();
            String keyword = request.getParameter("keyword");
            if (WebUtils.isValidateRealString(keyword)) {
                likeStrings.put("principalName", keyword);
                likeStrings.put("germchit", keyword);
                likeStrings.put("fertilizer", keyword);
                likeStrings.put("drug", keyword);
            }
            queryEntity.setLikeStrings(likeStrings);
            queryEntity.setBeginCreateTime(WebUtils.stringToData(request.getParameter("start_date")));
            queryEntity.setEndCreateTime(WebUtils.stringToData(request.getParameter("end_date")));
            queryEntity.setDateKeyword("cropTime");
            PageModel<CropCare> page = new PageModel();
            page.setPageSize(5);
            int pageNo = Integer.valueOf(request.getParameter("pageNo"));
            page.setPageNo(pageNo);
            List<CropCare> cropCareList = cropCareService.queryCropCarePage(queryEntity, page);
            JsonArray array = new JsonArray();
            for (CropCare cropCare : cropCareList) {
                JsonObject list = new JsonObject();
                list.addProperty("cropCareId", cropCare.getCropCareId());
                list.addProperty("landId", cropCare.getLandByLandId().getLandId());
                list.addProperty("landName", cropCare.getLandByLandId().getLandName());
                list.addProperty("batch", cropCare.getBatch());
                list.addProperty("principalName", cropCare.getPrincipalName());
                list.addProperty("germchit", cropCare.getGermchit());
                list.addProperty("count", cropCare.getCount());
                list.addProperty("fertilizer", cropCare.getFertilizer());
                list.addProperty("drug", cropCare.getDrug());
                list.addProperty("cropTime", WebUtils.timestampToString(cropCare.getCropTime()));
                array.add(list);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminCropCareController.getCropCareList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/updateCropCare")
    @ResponseBody
    public String updateCropCare(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            int cropCareId = Integer.valueOf(request.getParameter("cropCareId"));
            int landId = Integer.valueOf(request.getParameter("landId"));
            Integer batch = Integer.valueOf(request.getParameter("batch"));
            String principalName = request.getParameter("principalName");
            String germchit = request.getParameter("germchit");
            Integer count = Integer.valueOf(request.getParameter("count"));
            String fertilizer = request.getParameter("fertilizer");
            String drug = request.getParameter("drug");
            Timestamp cropTime = WebUtils.stringToTimestamp(request.getParameter("cropTime"));

            CropCare cropCare = cropCareService.queryCropCareById(cropCareId);
            cropCare.setLandByLandId(landService.queryLandById(landId));
            cropCare.setBatch(batch);
            cropCare.setPrincipalName(principalName);
            cropCare.setGermchit(germchit);
            cropCare.setCount(count);
            cropCare.setFertilizer(fertilizer);
            cropCare.setDrug(drug);
            cropCare.setCropTime(cropTime);

            cropCareService.updateCropCare(cropCare);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminCropCare.update()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/cropCareAdd")
    public ModelAndView initUserAddPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("landList", landService.getLandList());
        model.setViewName(addCropCarePage);
        return model;
    }

    @RequestMapping("/cropCareList")
    public ModelAndView initUserListPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("landList", landService.getLandList());
        model.setViewName(cropCareListPage);
        return model;
    }

}
